//
//  SelectProvinceViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/28.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "SelectProvinceViewController.h"
#import "GetAllProvincesResponse.h"
#import "ProductData.h"
#import "MultiProvinceData.h"

@interface SelectProvinceViewController ()

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSIndexPath *oldIndexPath;

@end

@implementation SelectProvinceViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
    self.oldIndexPath = nil;
}

#pragma mark - 初始化视图
- (void)setupViews{
    //自定义完成选择按钮
//    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成选择" style:UIBarButtonItemStyleDone target:self action:@selector(onSave)];
//    self.navigationItem.rightBarButtonItem = saveBtn;
    
    //自定义返回按钮
    UIBarButtonItem *returnBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onReturn)];
    self.navigationItem.leftBarButtonItem = returnBtn;
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    //[self loadNationData];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.selectedNation && self.selectedNation.count > 0) {
        for (ProvinceData *item in self.selectedNation) {
            [self loadProvinceData:item.guidId];
        }
    }
}


-(void)loadProvinceData:(NSString*)nationId {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:nationId forKey:@"nid"];
    
    [HttpClient getWithUrl:HTTP_GET_PROVINCES paramDic:dic resultClass:[GetAllProvincesResponse class] success:^(GetAllProvincesResponse *response) {
        if (response.getAllProvincesResult.count > 0) {
            MultiProvinceData *item = [MultiProvinceData new];
            item.data = [NSMutableArray new];
            
            for (ProvinceData *item1 in response.getAllProvincesResult) {
                //判断是否有省份已经在选择的数据里
                BOOL hasSelected = NO;
                ProvinceData *hasSelectedItem = nil;
                for (ProvinceData *selected in self.selectedData) {
                    if ([selected.guidId isEqualToString:item1.guidId]) {
                        hasSelected = YES;
                        hasSelectedItem = selected;
                        hasSelectedItem.name = item1.name;
                        hasSelectedItem.isSelected = YES;
                        break;
                    }
                }
                if (hasSelected) {
                    [item.data addObject:hasSelectedItem];
                }
                else {
                    [item.data addObject:item1];
                }
                
            }
            [self.dataSource addObject:item];
            [self.tableView reloadData];
        }
        else {
            NSLog(@"请求省份失败！");
        }
        
    } failure:^(NSError *error) {
        CMLog(@"请求省份失败！，错误信息为%@",error);
    }];
}

#pragma mark - 事件响应
- (void)onSave {
    if (self.selectedData.count == 0) {
        kTipAlert(@"您还没有选择省份！");
        return;
    }
    if (self.userSelectedBlock != nil) {
        self.userSelectedBlock(self.selectedData);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onReturn {
    if (self.selectedData.count == 0) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"您还没有选择省份" cancelButtonTitle:@"继续选择" otherButtonTitles:[NSArray arrayWithObjects:@"不选了", nil] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                return;
            }
            else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        return;
    }
    if (self.userSelectedBlock != nil) {
        self.userSelectedBlock(self.selectedData);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIAlertViewDelegate 代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        return;
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataSource.count > section) {
        MultiProvinceData *item = [self.dataSource objectAtIndex:section];
        return item.data.count;
    }
    return 0;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"NationCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
    cell.detailTextLabel.textColor = CM_TABLE_INFO_COLOR;
    MultiProvinceData *provinceData = [self.dataSource objectAtIndex:indexPath.section];
    ProvinceData *item = [provinceData.data objectAtIndex:indexPath.row];
    cell.textLabel.text = item.name;
    if (item.isSelected) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        if (!self.couldMultipleSelect) {
            self.oldIndexPath = indexPath;
        }
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MultiProvinceData *provinceData = [self.dataSource objectAtIndex:indexPath.section];
    ProvinceData *item = [provinceData.data objectAtIndex:indexPath.row];
    if (self.selectedData == nil) {
        self.selectedData = [NSMutableArray new];
    }
    if (self.couldMultipleSelect) {
        //多选
        item.isSelected = !item.isSelected;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        if (item.isSelected) {
            [self.selectedData addObject:item];
        }
        else {
            [self.selectedData removeObject:item];
        }
        
        //给出提示
        NSMutableString *selectStr = [NSMutableString new];
        if (self.selectedData.count > 0) {
            [selectStr appendString:@"您已经选择了："];
            for (ProvinceData *selected in self.selectedData) {
                [selectStr appendString:selected.name];
                [selectStr appendString:@" "];
            }
        }
        else {
            [selectStr appendString:@"您当前没有选择省份"];
        }
        [Tools showMessageCenter:selectStr];
    }
    else {
        [self.selectedData removeAllObjects];
        [self.selectedData addObject:item];
        if (self.userSelectedBlock != nil) {
            self.userSelectedBlock(self.selectedData);
        }
        [self.navigationController popViewControllerAnimated:YES];
//        if (self.oldIndexPath == nil) {
//            item.isSelected = !item.isSelected;
//            self.oldIndexPath = indexPath;
//            [self.selectedData addObject:item];
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//        }
//        else if (self.oldIndexPath == indexPath){
//            item.isSelected = !item.isSelected;
//            if (item.isSelected) {
//                [self.selectedData addObject:item];
//            }
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//        }
//        else {
//            item.isSelected = YES;
//            [self.selectedData addObject:item];
//            
//            MultiProvinceData *oldData = [self.dataSource objectAtIndex:self.oldIndexPath.section];
//            ProvinceData *oldItem = [oldData.data objectAtIndex:self.oldIndexPath.row];
//            oldItem.isSelected = NO;
//            
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, self.oldIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//            self.oldIndexPath = indexPath;
//        }
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
